package com.cmol.peopledetectapp.user;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.cmol.data.CodeUtils;
import com.cmol.data.Host;
import com.cmol.net.Network;
import com.cmol.peopledetectapp.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.Proxy;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 用户注册
 *
 * @author 张瀚文 邢文成
 */
public class RegisterActivity extends AppCompatActivity {

    // 发送邮件结果
    String emailResult = new String();
    String codeStr;
    /**
     * 通信模块
     */
    private Network network;
    private EditText email;
    private EditText password;
    private EditText securityCode, emailCode;
    private ImageView imageView, test;
    private Random rand;
    private File output;
    private InputStream fis;
    private Uri imageUri;
    private byte[] bytes;
    private RegisterActivity registerActivity;
    private CodeUtils codeUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rand = new Random();
        setContentView(R.layout.activity_register);
        email = findViewById(R.id.registerAccount);
        password = findViewById(R.id.registerPassword);
        securityCode = findViewById(R.id.verification);
        imageView = findViewById(R.id.SecuritCode);
        emailCode = findViewById(R.id.verification2);
        test = findViewById(R.id.test);

        initView();
    }

    @Override
    protected void onStart() {
        super.onStart();
        output = new File(getExternalCacheDir(), "output_image.jpg");
        FileInputStream is = null;
        try {
            is = new FileInputStream(output);
            bytes = new byte[is.available()];
            is.read(bytes, 0, is.available());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 初始化界面，同时生成初始图形验证码
     */
    public void initView() {
        imageView.setOnClickListener(new ImageClick());
        codeUtils = CodeUtils.getInstance();
        Bitmap bitmap = codeUtils.createBitmap();
        imageView.setImageBitmap(bitmap);
    }

    /**
     * 点击注册
     *
     * @param view 布局文件
     */
    public void RegisterClick(View view) {
        String patternAccount = "^0?[A-Z a-z0-9]+@[A-Z a-z 0-9]+\\.com";
        String patternPassword = "^[A-Z a-z0-9]+";
        String account = email.getText().toString();
        String pwd = password.getText().toString();
        String code = emailCode.getText().toString();
        output = new File(getExternalCacheDir(), "output_image.jpg");
//        bytes = registerActivity.pictureToBytearray(output);

//        Log.e("=================",account);
//        Log.e("====================", pwd);
//        Log.e("===========================", String.valueOf(account.matches(patternAccount) && pwd.matches(patternPassword)));
        if (account.matches(patternAccount) && pwd.matches(patternPassword)) {
            boolean pver = pictureVerify();
            if (pver) {
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("account", account);
                    jsonObject.put("password", pwd);
                    jsonObject.put("code", code);
                    jsonObject.put("image", bytes);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(RegisterActivity.this, "正在登陆", Toast.LENGTH_SHORT).show();
                    }
                });
                /*
                 * 通信等待参数
                 */
                OkHttpClient okHttpClient = new OkHttpClient.Builder()
                        .connectTimeout(10, TimeUnit.SECONDS)
                        .readTimeout(10, TimeUnit.SECONDS)
                        .writeTimeout(10, TimeUnit.SECONDS)
                        .proxy(Proxy.NO_PROXY)
                        .build();
                MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
                RequestBody requestBody = RequestBody.create(mediaType, "" + jsonObject.toString());
                Request request = new Request.Builder()
                        .url(Host.host + "/user/register")
//                .addHeader("Authorization", GlobalData.getUserToken())
                        .post(requestBody)
                        .build();
                Log.e("requestBody", requestBody.toString());
                Call call = okHttpClient.newCall(request);
                /*
                 * 异步响应
                 */
                call.enqueue(new Callback() {
                    /**
                     * Called when the request could not be executed due to cancellation, a connectivity problem or
                     * timeout. Because networks can fail during an exchange, it is possible that the remote server
                     * accepted the request before the failure.
                     *
                     * @param call
                     * @param e
                     */
                    @Override
                    public void onFailure(Call call, IOException e) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Log.e("==============body:", e.toString());
                                Toast.makeText(RegisterActivity.this, "网络请求异常", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    /**
                     * Called when the HTTP response was successfully returned by the remote server. The callback may
                     * proceed to read the response body with . The response is still live until
                     * its response body is {@linkplain ResponseBody closed}. The recipient of the callback may
                     * consume the response body on another thread.
                     *
                     * <p>Note that transport-layer success (receiving a HTTP response code, headers and body) does
                     * not necessarily indicate application-layer success: {@code response} may still indicate an
                     * unhappy HTTP response code like 404 or 500.
                     *
                     * @param call
                     * @param response
                     */
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String res = Objects.requireNonNull(response.body()).string().trim();
//                Log.e("=====================res",response.toString());
                        Log.e("====body: ", res);
                        if (response.code() == 200) {
                            try {
                                JSONObject json = new JSONObject(res);
                                /**
                                 * token:
                                 * boolean auth:
                                 */
                                String auth = "";
                                auth = json.getString("auth");

                                if (auth.equals("0")) {
                                    Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                                    Log.e("跳转=======", "111");
//                                    startActivity(new Intent(RegisterActivity.this, MainActivity.class));
                                    finish();
                                } else if (auth.equals("1")) {
                                    Toast.makeText(RegisterActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
                                } else if (auth.equals("2")) {
                                    Toast.makeText(RegisterActivity.this, "人脸信息已存在", Toast.LENGTH_SHORT).show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(RegisterActivity.this, "服务器异常" + response.code(), Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                    }
                });


//                // 指令
//                network = new Network(jsonObject, "/user/register") {
//                    @Override
//                    protected void process(Call call, Response response) {
//                        try {
//                            System.out.println("代码：" + response.code());
//                            System.out.println("开始接收：");
//                            System.out.println(response);
//                            final String body = Objects.requireNonNull(response.body()).string().trim();
//                            JSONObject res = new JSONObject(body);
//                            String result = res.getString("auth");
//                            System.out.println("响应：" + result);
//                            if(result.equals("0")){
//                                Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
//                                startActivity(new Intent(RegisterActivity.this, MainActivity.class));
//                                finish();
//                            }else if(result.equals("1")){
//                                Toast.makeText(RegisterActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
//                            }else if(result.equals("2")){
//                                Toast.makeText(RegisterActivity.this, "人脸信息已存在", Toast.LENGTH_SHORT).show();
//                            }
//                        } catch (IOException | JSONException e) {
//                            e.printStackTrace();
//                        }
//                    }
//
//                    @Override
//                    protected void failureWarn() {
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                Toast.makeText(RegisterActivity.this, "注册失败", Toast.LENGTH_SHORT).show();
//                            }
//                        });
//                    }
//                };
            }
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.e(" =================", "run:========================= ");
                    Toast.makeText(RegisterActivity.this, "请输入正确格式的邮箱和密码", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

//    public byte[] pictureToBytearray(File src) {
//        byte[] array_flush = null;
//        InputStream pictureToProgram = null;
//        ByteArrayOutputStream programToArray = null;
//
//        try {
//            pictureToProgram = new FileInputStream(src);
//            programToArray = new ByteArrayOutputStream();
//        } catch (FileNotFoundException e1) {
//            e1.printStackTrace();
//        }
//        //操作：图片输入程序
//        byte[] temp_flush = new byte[1024*10];
//        int len = -1;
//        try {
//            while((len=pictureToProgram.read(temp_flush))!=-1) {
//                //程序输出到数组
//                programToArray.write(temp_flush, 0, len);
//            }
//            programToArray.flush();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        //程序输出到数组
//        array_flush = programToArray.toByteArray();
//        //释放
//        if(null!=pictureToProgram) {
//            try {
//                pictureToProgram.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            //System.out.println("pictureToProgram释放成功");
//        }
//        return array_flush;
//    }


    /**
     * 验证码验证
     *
     * @return
     */
    private boolean pictureVerify() {
        boolean pver = false;
        codeStr = securityCode.getText().toString().trim();
        Log.e("codeStr", codeStr);
        if (null == codeStr || TextUtils.isEmpty(codeStr)) {
            Toast.makeText(this, "请输入验证码", Toast.LENGTH_SHORT).show();
            pver = false;
            return pver;
        }
        String code = codeUtils.getCode();
        Log.e("code", code);
        if (code.equalsIgnoreCase(codeStr)) {
//            Toast.makeText(this, "验证码正确", Toast.LENGTH_SHORT).show();
            pver = true;
            return pver;

        } else {
            Toast.makeText(this, "验证码错误", Toast.LENGTH_SHORT).show();
            pver = false;
            return pver;
        }
    }

    public void FaceClick(View view) {
        Intent intent = new Intent(this, FaceRecognitionActivity.class);
        // 传递调用类型 1（注册）
        intent.putExtra("type", "1");
        startActivity(intent);
    }

    public void EmailClick1(View view) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .proxy(Proxy.NO_PROXY)
                .build();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("account", email.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        RequestBody requestBody = RequestBody.create(mediaType, "" + jsonObject.toString());
        Request request = new Request.Builder()
                .url(Host.host + "/user/sendEmail")
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            /**
             * Called when the request could not be executed due to cancellation, a connectivity problem or
             * timeout. Because networks can fail during an exchange, it is possible that the remote server
             * accepted the request before the failure.
             *
             * @param call
             * @param e
             */
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("==============body:", e.toString());
                        Toast.makeText(RegisterActivity.this, "网络请求异常", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            /**
             * Called when the HTTP response was successfully returned by the remote server. The callback may
             * proceed to read the response body with . The response is still live until
             * its response body is {@linkplain ResponseBody closed}. The recipient of the callback may
             * consume the response body on another thread.
             *
             * <p>Note that transport-layer success (receiving a HTTP response code, headers and body) does
             * not necessarily indicate application-layer success: {@code response} may still indicate an
             * unhappy HTTP response code like 404 or 500.
             *
             * @param call
             * @param response
             */
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String res = Objects.requireNonNull(response.body()).string().trim();
                if (response.code() == 200) {
                    try {
                        JSONObject js = new JSONObject(res);
                        // 接收服务器反馈的提示信息
                        emailResult = js.getString("auth");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }
        });
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (emailResult.equals("0")) {
            Toast.makeText(RegisterActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
            // "1" 邮箱已被注册
        } else if (emailResult.equals("1")) {
            Toast.makeText(RegisterActivity.this, "邮箱已被注册", Toast.LENGTH_SHORT).show();
            // "2" 邮箱不存在
        } else if (emailResult.equals("2")) {
            Toast.makeText(RegisterActivity.this, "邮箱不存在", Toast.LENGTH_SHORT).show();
        }
    }

    public void EmailClick(View view) {
        // 发送邮箱验证码
        JSONObject tmp = new JSONObject();
        try {
            tmp.put("account", email.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        network = new Network(tmp, "/user/sendEmail") {
            @Override
            protected void process(Call call, Response response) throws IOException {
                String ans = Objects.requireNonNull(response.body()).string().trim();
                try {
                    JSONObject js = new JSONObject(ans);
                    // 接收服务器反馈的提示信息
                    emailResult = js.getString("auth");
                    // "0" 发送成功
                    if (emailResult.equals("0")) {
                        Toast.makeText(RegisterActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                        // "1" 邮箱已被注册
                    } else if (emailResult.equals("1")) {
                        Toast.makeText(RegisterActivity.this, "邮箱已被注册", Toast.LENGTH_SHORT).show();
                        // "2" 邮箱不存在
                    } else if (emailResult.equals("2")) {
                        Toast.makeText(RegisterActivity.this, "邮箱不存在", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void failureWarn() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(RegisterActivity.this, "网络请求异常", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        };
    }

    /**
     * 点击更换图形验证码
     */
    class ImageClick implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            codeUtils = CodeUtils.getInstance();
            Bitmap bitmap = codeUtils.createBitmap();
            imageView.setImageBitmap(bitmap);
        }
    }
}